//
//  ZXNetWorkingManager.swift
//  loveBee
//
//  Created by zhangxing on 2017/8/12.
//  Copyright © 2017年 zhangXing. All rights reserved.
//

import UIKit
//因为我们继承自AFHTTPSessionManager,所以我们需要导入头文件AFNetworking,否则报错
import AFNetworking

//定义枚举类型
enum RequestType {
    //get请求
    case get
    //post请求
    case post
    
}


class ZXNetWorkingManager: AFHTTPSessionManager {
    
    //静态对象
    static var sharedManager: ZXNetWorkingManager = {
        
        let manager = ZXNetWorkingManager()
        //添加网络管理者的可接受的响应类型html
        manager.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        //添加网络管理者的可接受的响应类型plain
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        ////申明请求的数据是json类型
        manager.requestSerializer = AFJSONRequestSerializer()
        
        
        return manager
        
    }()
    
    
    //  MARK: --   实现网络情况方法
    fileprivate func sendRequest(requestType: RequestType, URLName: String, parameters: Any?, backCallClosure: @escaping(Any?, Error?) -> ()) {
        
        //如果是get请求
        if requestType == .get {
            
            get(URLName, parameters: parameters, progress: nil, success: { (_, respond) in
                backCallClosure(respond, nil)
            }, failure: { (_, error) in
                backCallClosure(nil, error)
            })
        }
        else {
            
            post(URLName, parameters: parameters, progress: nil, success: { (_, respond) in
                backCallClosure(respond, nil)
            }, failure: { (_, error) in
                backCallClosure(nil, error)
            })
        }
        
        
    }
   
}

//获取网络数据
extension ZXNetWorkingManager {
    
    //因为这里的每一个请求都是post类型的,且只需要一个URLStr,还有一个Call就可以了,所以我们采取了封装方法gainAppInfo,因为我们这里的方法是在extension里面,所以sendRequest方法定义成了fileprivate类型的
    func gainAppInfo(URLStr: String, call: String, callBackClosure: @escaping(Any?, Error?) -> ()) {
        
        let parameters = ["call" : call]
        
        sendRequest(requestType: .post, URLName: URLStr, parameters: parameters, backCallClosure: callBackClosure)
        
    }
    
    
    
    
}










